﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GpsAddIn2003.Core;
using Dal;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using System.Security.Cryptography;
using System.Xml;
using System.Diagnostics;

namespace GpsAddIn2003
{
    public partial class MainFrm : Form
    {
        System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
        public static DataTable dt = new DataTable();
        private delegate void MyAsyncDelegate();
        /// <summary>  
        /// 执行方法  
        /// </summary>  
        /// <returns></returns>  
        private void DoAsyncEvent()
        {
            try
            {
                dt = Gps_Dal.get_FullCarInfo();
                Thread.Sleep(1000);
                GetValueBySQL();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }
        /// <summary>  
        /// 回调函数得到异步线程的返回结果  
        /// </summary>  
        /// <param name="iasync"></param>  
        private static void CallBack(IAsyncResult iasync)
        {
            AsyncResult async = (AsyncResult)iasync;
            MyAsyncDelegate del = (MyAsyncDelegate)async.AsyncDelegate;
            del.EndInvoke(iasync);
        }
        public MainFrm()
        {
            InitializeComponent();
            #region 隐藏Excel单据界面
            Globals.ThisAddIn.Application.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlNormal;
            Globals.ThisAddIn.Application.Height = 5;
            Globals.ThisAddIn.Application.Width = 5;
            Globals.ThisAddIn.Application.Top = Screen.PrimaryScreen.WorkingArea.Height;
            Globals.ThisAddIn.Application.Left = Screen.PrimaryScreen.WorkingArea.Left;
            #endregion
            this.WindowState = FormWindowState.Maximized;
            //-------------------------------------------------
            MyAsyncDelegate del = new MyAsyncDelegate(DoAsyncEvent);
            del.BeginInvoke(new AsyncCallback(CallBack), null);
            Thread.Sleep(1000);
            GetValueBySQL();
            //--------------------------------------------------
            myTimer.Interval = 1000 * 60;
            myTimer.Enabled = true;
            myTimer.Tick += new EventHandler(myTimer_Tick);
            myTimer.Start();
        }


        private void myTimer_Tick(object sender, EventArgs e)
        {
            
            MyAsyncDelegate del = new MyAsyncDelegate(DoAsyncEvent);
            del.BeginInvoke(new AsyncCallback(CallBack), null);
        }
        private void GetValueBySQL()
        {
            
            if (this.dataGridView1.InvokeRequired)
            {
                this.dataGridView1.Invoke((MethodInvoker)delegate { this.FillData(); });
            }
            else
            {
                this.FillData();
            }

            if (this.ll_Time.InvokeRequired == true)
            {
                this.ll_Time.Invoke((MethodInvoker)delegate { this.Fill_ll_Time(); });
            }
            else
            {
                Fill_ll_Time();
            }

            if (this.label_CarCount.InvokeRequired == true)
            {
                this.label_CarCount.Invoke((MethodInvoker)delegate { this.Fill_label_CarCount(); });
            }
            else
            {
                Fill_label_CarCount();
            }
            if (this.label_repear.InvokeRequired == true)
            {
                this.label_repear.Invoke((MethodInvoker)delegate { this.Fill_label_repear(); });
            }
            else
            {
                Fill_label_repear();
            }
            if (this.label_kdd.InvokeRequired == true)
            {
                this.label_kdd.Invoke((MethodInvoker)delegate { this.Fill_label_kdd(); });
            }
            else
            {
                Fill_label_kdd();
            }
        }
        private void FillData()
        {
            dataGridView1.DataSource = FillToTable(dt);
        }
        private void Fill_ll_Time()
        {
            ll_Time.Text = "上次刷新时间：" + DateTime.Now.ToString();
        }
        private void Fill_label_CarCount()
        {
            if (dt != null && dt.TableName != "")
                label_CarCount.Text = dt.Compute("sum(在线)", "").ToString();
        }
        private void Fill_label_repear()
        {
            if (dt != null && dt.TableName != "")
                label_repear.Text = dt.Compute("sum(维修)", "").ToString();
        }
        private void Fill_label_kdd()
        {
            if (dt != null && dt.TableName != "")
            {
                label_kdd.Text = dt.Compute("sum(已派车)", "").ToString() == "" ? "0" : dt.Compute("sum(已派车)", "").ToString();
            }
        }
        private DataTable FillToTable(DataTable dt)
        {
            DataTable myDt = new DataTable();
            myDt.Columns.Add("车队", typeof(string));
            myDt.Columns.Add("拥有量", typeof(int));
            myDt.Columns.Add("维修", typeof(int));
            myDt.Columns.Add("在线", typeof(int));
            myDt.Columns.Add("运行", typeof(int));
            myDt.Columns.Add("停用", typeof(int));
            myDt.Columns.Add("已派车", typeof(int));
            myDt.Columns.Add("可派车", typeof(int));
            myDt.Columns.Add("报警", typeof(int));
            myDt.Columns.Add("油位", typeof(int));
            myDt.Columns.Add("超速", typeof(int));
            myDt.Columns.Add("越界", typeof(int));
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow lvRow = myDt.NewRow();
                    lvRow["车队"] = dt.Rows[i]["车队"].ToString();
                    lvRow["拥有量"] = dt.Rows[i]["拥有量"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["拥有量"].ToString());
                    lvRow["维修"] = dt.Rows[i]["维修"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["维修"].ToString());
                    lvRow["在线"] = dt.Rows[i]["在线"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["在线"].ToString());
                    lvRow["运行"] = dt.Rows[i]["运行"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["运行"].ToString());
                    lvRow["报警"] = dt.Rows[i]["报警"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["报警"].ToString());
                    lvRow["停用"] = dt.Rows[i]["停用"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["停用"].ToString());
                    lvRow["已派车"] = dt.Rows[i]["已派车"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["已派车"].ToString());
                    lvRow["可派车"] = int.Parse(lvRow["拥有量"].ToString()) - int.Parse(lvRow["已派车"].ToString()) - int.Parse(lvRow["维修"].ToString());
                    lvRow["油位"] = dt.Rows[i]["油位"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["油位"].ToString());
                    lvRow["超速"] = dt.Rows[i]["超速"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["超速"].ToString());
                    lvRow["越界"] = dt.Rows[i]["越界"].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["越界"].ToString());
                    myDt.Rows.Add(lvRow);
                }

                return myDt;
            }
            else
            {
                return myDt;
            }

        }
        /// <summary>
        /// 获取单元格集合的数据集返回datatable型
        /// </summary>
        /// <param name="rng"></param>
        /// <returns></returns>
        public DataTable rangeTable(Microsoft.Office.Interop.Excel.Range rng)
        {
            DataTable dt = new DataTable();
            int rowCnt = rng.Rows.Count;
            int colCnt = rng.Columns.Count;

            for (int i = 1; i <= rowCnt; i++)
            {
                DataRow newRow = dt.NewRow();
                for (int j = 1; j <= colCnt; j++)
                {
                    if (i == 1)
                    {
                        dt.Columns.Add(((Microsoft.Office.Interop.Excel.Range)rng.get_Item(i, j)).Value2.ToString(), typeof(string));
                    }
                    else
                    {
                        newRow[j - 1] = ((Microsoft.Office.Interop.Excel.Range)rng.get_Item(i, j)).Value2;
                    }
                }
                if (i > 1)
                {
                    dt.Rows.Add(newRow);
                }
            }
            return dt;

        }

        private void panel_Car_Click(object sender, EventArgs e)
        {
            try
            {
                Globals.ThisAddIn.Application.Run("showCarList_Event", Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void panel_repear_Click(object sender, EventArgs e)
        {
            try
            {
                Globals.ThisAddIn.Application.Run("showRepearList_Event", Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void panel_bill_Click(object sender, EventArgs e)
        {
            try
            {
                Globals.ThisAddIn.Application.Run("showBillList_Event", Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (dataGridView1.SelectedCells[0].Value.ToString() != "0")
                {
                    string ColName = dataGridView1.Columns[e.ColumnIndex].Name;
                    string CellValue = dataGridView1.Rows[e.RowIndex].Cells["车队"].Value.ToString();
                    Globals.ThisAddIn.Application.Run("CellDoubleClick_Event", ColName, CellValue,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                }
                else
                {
                    MessageBox.Show("数值为0，没有数据可供查询！");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void MainFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            myTimer.Stop();
            myTimer.Enabled = false;
            #region 显示Excel单据界面
            Globals.ThisAddIn.Application.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMaximized;
            #endregion
            Globals.ThisAddIn.Application.Quit();
        }

        private void label_kdd_Click(object sender, EventArgs e)
        {
            try
            {
                Globals.ThisAddIn.Application.Run("showkddList_Event", Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void MainFrm_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.F12)
            {
                myTimer.Stop();
                myTimer.Enabled = false;
                Globals.ThisAddIn.Application.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMaximized;
            }
        }
    }
}
